package com.kaishengit.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.kaishengit.entity.User;
import com.kaishengit.util.db.DBHelp;
import com.kaishengit.util.db.RowMapper;

public class UserDao {
	
	private DBHelp<User> db=new DBHelp<User>()	;
	
	public User findByNameAndPassword(String username, String password){
	
		String sql="select id,username,password,pic from t_user where username=? and password=?";
		return db.executeQueryToObject(sql, new UserRowMapper(),username,password);
	}
	
	public User findByName(String name){
		String sql = "select id,username,password,pic from t_user where username=?";
		return db.executeQueryToObject(sql, new UserRowMapper(), name);
	}
	
	public void save(User user){
		String sql="insert into t_user(username,password,pic) values(?,?,?)"; 
		db.executeSQL(sql, user.getUsername(),user.getPassword(),user.getPic());	
	}
	public void  update(User user){
		String sql="update t_user set username=?,password=?,pic=? where id=?";
		db.executeSQL(sql, user.getUsername(),user.getPassword(),user.getPic());	
	}
	
	public void del(User user){
		String sql="delete id,username,password,pic where id=?";
		db.executeQuery(sql, user.getId());
	}
	public User findById(int id) {
		String sql="select id,username,password,pic from t_user where id=? ";
		return db.executeQueryToObject(sql, new UserRowMapper(),id);
	}
	
	public List<User> findAllUser() {
		String sql = "select id,username,password,pic from t_user";
		return db.executeQueryToList(sql, new UserRowMapper());
	}

	private  class UserRowMapper implements RowMapper<User> {
		public User mapRow(ResultSet rs) throws SQLException {
			
			User user=new User();
			user.setId(rs.getInt("id"));
			user.setUsername(rs.getString("username"));
			user.setPassword(rs.getString("password"));
			user.setPic(rs.getString("pic"));
			return user;
		}	
	}
	
}
